package com.whlilong.jxc.db;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.whlilong.jxc.util.FileUtil;

public class HibernateSessionFactory {
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static final Configuration cfg = new Configuration();
	private static SessionFactory sf;
	static {
		try {
			File file = new File(FileUtil.getWorkspace(),
					"hibernate_derby.cfg.xml");
			cfg.configure(file);
			sf = cfg.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Session getSession(String file) throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			session = (sf == null) ? null : sf.openSession();
			threadLocal.set(session);
		}
		return session;
	}

	@SuppressWarnings("deprecation")
	public static void close() throws SQLException {
		if (sf != null) {
			Connection con = sf.openSession().connection();
			con.commit();
			PreparedStatement st = con.prepareStatement("SHUTDOWN");
			st.execute();
			con.close();
			org.hsqldb.DatabaseManager.closeDatabases(0);
		}

	}

	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null)
			session.close();
	}

	private HibernateSessionFactory() {
	}
}